import os
import time


# node1
def TestIFIO():
    input_file = "/tmp/node2_to_node1.tmp"
    output_file = "/tmp/node1_to_node2.tmp"

    # 1.create fifo
    if not os.path.exists(input_file):
        os.mkfifo(input_file, 0o666)
    if not os.path.exists(output_file):
        os.mkfifo(output_file, 0o666)

    # 2.open pipe
    print('init write pipe: ' + output_file)
    fout = os.open(output_file, os.O_WRONLY)
    print('init read pipe:  ' + input_file)
    fin = os.open(input_file, os.O_RDONLY)

    # 3.write and read data
    send_str = "How are you?"
    while True:
        try:
            os.write(fout, str.encode(send_str))
        except:
            print("node2 closed, exit!")
            break
        print("send: ", send_str)

        recv_str = os.read(fin, 1024).decode()[:-1]  # strip '\0'
        print("recv: ", recv_str)
        time.sleep(0.5)

    os.close(fin)
    os.close(fout)


if __name__ == '__main__':
    TestIFIO()
